package com.example.demo.aspect;


import org.apache.commons.lang3.time.StopWatch;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class TimeInterceptor {

    Logger logger = LoggerFactory.getLogger(TimeInterceptor.class);

    //ok
    public static final String POINT_SDK = "execution(* com.example.demo.service.*.*(..))";

    //ok
    public static final String POINT_SDK_1 = "execution(* com.example.demo.service1.impl.TestService3Impl.*(..))";

    // fail
    public static final String POINT_SDK_2 = "execution(* com.example.demo.service1.impl.TestService2Impl.*(..))";

    // fail
    public static final String POINT_SDK_3 = "execution(* com.example.demo.service1.impl.TestService4Impl.test(..))";

    //ok
    public static final String POINT_SDK_4 = "execution(* com.example.demo.service1.impl.TestService4Impl.run(..))";

    //fail
    public static final String POINT_SDK_5 = "execution(* com.example.demo.service1.impl.TestService5Impl.test(..))";

    //ok
    public static final String POINT_SDK_6 = "execution(* com.example.demo.service1.impl.TestService5Impl.handle(..))";

    // ok
    public static final String POINT_SDK_7 = "execution(* com.example.demo.service1.impl.TestService6Impl.handle(..))";

    //ok
    public static final String POINT_SDK_8 = "execution(* com.example.demo.service1.impl.TestService6Impl.handle(..))";

    //fail
    public static final String POINT_SDK_9 = "execution(* com.example.demo.service1.impl.TestService7Impl.testaa(..))";


    @Around(POINT_SDK_9)
    public Object timeAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String methodName = signature.getDeclaringTypeName() + "." + signature.getName();

        StopWatch clock = new StopWatch();
        clock.start();

        try {
            Object obj = joinPoint.proceed(args);
            return obj;
        } finally {
            clock.stop();
            logger.info("method({}) cost({})", methodName, clock.getTime());
        }
    }
}
